<template>
  <div class="home-page">
    <!-- 快捷创建区域 -->
    <div class="quick-actions tw:flex">
      <div class="quick-actions-card">
        <div class="card-header" @click="$router.push('/ask')">
          <el-avatar
            :size="32"
            :src="getMediaUrl(userStore.userInfo?.avatar)"
            :alt="userStore.nickname"
          >
            {{ userStore.nickname.charAt(0) }}
          </el-avatar>
          <input
            type="text"
            placeholder="What do you want to ask or share?"
            readonly
            class="action-input"
          />
        </div>
        <div class="card-footer">
          <button class="action-btn" @click="$router.push('/write')">
            <svg viewBox="0 0 24 24" width="18" height="18">
              <path
                d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"
                fill="currentColor"
              />
            </svg>
            <span>Ask</span>
          </button>
          <div class="divider"></div>
          <button class="action-btn" @click="$router.push('/ask')">
            <svg viewBox="0 0 24 24" width="18" height="18">
              <path
                d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"
                fill="currentColor"
              />
            </svg>
            <span>Answer</span>
          </button>
          <div class="divider"></div>
          <button class="action-btn" @click="$router.push('/write')">
            <svg viewBox="0 0 24 24" width="18" height="18">
              <path
                d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"
                fill="currentColor"
              />
            </svg>
            <span>Post</span>
          </button>
        </div>
      </div>
    </div>

    <!-- 顶部导航标签 -->
    <!-- <div class="home-tabs">
      <div class="tabs-container">
        <div
          v-for="tab in tabs"
          :key="tab.key"
          class="tab-item"
          :class="{ active: activeTab === tab.key }"
          @click="switchTab(tab.key)"
        >
          {{ tab.label }}
        </div>
      </div>
    </div> -->

    <!-- 内容区域 -->
    <div class="home-content">
      <!-- <div v-if="hasMore" class="load-more">
        <el-button type="text" :loading="loadingMore" @click="loadMore">
          {{ loadingMore ? "加载中..." : "加载更多" }}
        </el-button>
      </div> -->

      <!-- 没有更多内容 -->
      <!-- <div v-else class="no-more">
        <span>没有更多内容了</span>
      </div> -->
      <!-- 推荐内容 -->
      <div v-if="activeTab === 'recommend'" class="content-list">
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="3" animated />
        </div>
        <div v-else>
          <ContentCard
            v-for="item in recommendList"
            :key="item.id"
            :data="item"
            @like="handleLike"
            @collect="handleCollect"
            @comment="handleComment"
            @share="handleShare"
          />

          <!-- 加载更多 -->
          <div v-if="hasMore" class="load-more">
            <el-button type="text" :loading="loadingMore" @click="loadMore">
              {{ loadingMore ? "加载中..." : "加载更多" }}
            </el-button>
          </div>

          <!-- 没有更多内容 -->
          <div v-else class="no-more">
            <span>没有更多内容了</span>
          </div>
        </div>
      </div>

      <!-- 关注内容 -->
      <div v-else-if="activeTab === 'following'" class="content-list">
        <div v-if="!userStore.isLoggedIn" class="login-prompt">
          <div class="prompt-content">
            <el-icon size="48" color="#8590a6">
              <User />
            </el-icon>
            <h3>登录后查看关注内容</h3>
            <p>关注你感兴趣的人，获取个性化推荐</p>
            <el-button type="primary" @click="$router.push('/login')">
              立即登录
            </el-button>
          </div>
        </div>
        <div v-else>
          <ContentCard
            v-for="item in followingList"
            :key="item.id"
            :data="item"
            @like="handleLike"
            @collect="handleCollect"
            @comment="handleComment"
            @share="handleShare"
          />
        </div>
      </div>

      <!-- 热榜 -->
      <div v-else-if="activeTab === 'hot'" class="content-list">
        <HotList :data="hotList" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user";
import ContentCard from "./components/ContentCard.vue";
import HotList from "./components/HotList.vue";
import {
  getFollowingContent,
  getHotContent,
  getRecommendContent,
} from "@/api/home";
import { toggleLikeArticle, toggleCollectArticle } from "@/api/article";
import { toggleLikeQuestion } from "@/api/question";
import { toggleLikeAnswer } from "@/api/answer";
import { shareContent } from "@/utils/clipboard";
import { getMediaUrl } from "@/utils/media";
const router = useRouter();
const userStore = useUserStore();

// 标签页配置
const tabs = [
  { key: "recommend", label: "Recommend" },
  { key: "following", label: "Following" },
  { key: "hot", label: "Hot" },
];

// 当前活跃标签
const activeTab = ref("recommend");

// 加载状态
const loading = ref(false);
const loadingMore = ref(false);
const hasMore = ref(true);

// 数据列表
const recommendList = ref([]);
const followingList = ref([]);
const hotList = ref([]);

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 切换标签
const switchTab = (tabKey) => {
  activeTab.value = tabKey;

  // 根据标签加载对应数据
  switch (tabKey) {
    case "recommend":
      if (recommendList.value.length === 0) {
        loadRecommendData();
      }
      break;
    case "following":
      if (userStore.isLoggedIn && followingList.value.length === 0) {
        loadFollowingData();
      }
      break;
    case "hot":
      if (hotList.value.length === 0) {
        loadHotData();
      }
      break;
  }
};

// 加载推荐数据
const loadRecommendData = async (isLoadMore = false) => {
  try {
    if (!isLoadMore) {
      loading.value = true;
      pagination.pageNum = 1;
    } else {
      loadingMore.value = true;
    }

    // 调用API获取推荐内容
    const response = await getRecommendContent({
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
    });

    if (response.code === 200) {
      const { data, total } = response.data;

      if (isLoadMore) {
        recommendList.value.push(...data);
      } else {
        recommendList.value = data;
      }

      pagination.pageNum++;

      // 检查是否还有更多数据
      const totalLoaded = isLoadMore ? recommendList.value.length : data.length;
      hasMore.value = totalLoaded < total;
    } else {
      ElMessage.error(response.message || "加载推荐内容失败");
    }
  } catch (error) {
    console.error("加载推荐数据失败:", error);
    ElMessage.error("加载推荐内容失败");
  } finally {
    loading.value = false;
    loadingMore.value = false;
  }
};

// 加载关注数据
const loadFollowingData = async () => {
  try {
    loading.value = true;

    // 调用API获取关注内容
    const response = await getFollowingContent({
      pageNum: 1,
      pageSize: 20,
    });

    if (response.code === 200) {
      followingList.value = response.data.data || [];
    } else {
      ElMessage.error(response.message || "加载关注内容失败");
    }
  } catch (error) {
    console.error("加载关注数据失败:", error);
    ElMessage.error("加载关注内容失败");
  } finally {
    loading.value = false;
  }
};

// 加载热榜数据
const loadHotData = async () => {
  try {
    loading.value = true;

    // 调用API获取热榜数据
    const response = await getHotContent(50);

    if (response.code === 200) {
      hotList.value = response.data || [];
    } else {
      ElMessage.error(response.message || "加载热榜数据失败");
    }
  } catch (error) {
    console.error("加载热榜数据失败:", error);
    ElMessage.error("加载热榜数据失败");
  } finally {
    loading.value = false;
  }
};

// 加载更多
const loadMore = () => {
  if (activeTab.value === "recommend") {
    loadRecommendData(true);
  }
};

// 点赞处理
const handleLike = async (item) => {
  // 检查登录状态
  if (!userStore.isLoggedIn) {
    ElMessage.warning("请先登录");
    return;
  }

  try {
    let response;
    // 根据内容类型调用不同的点赞API
    if (item.type === "article") {
      response = await toggleLikeArticle(item.id);
    } else if (item.type === "question") {
      response = await toggleLikeQuestion(item.id);
    } else if (item.type === "answer") {
      response = await toggleLikeAnswer(item.id);
    }

    if (response && response.code === 200) {
      // 更新本地状态
      item.isLiked = !item.isLiked;
      if (item.isLiked) {
        item.stats.likeCount++;
      } else {
        item.stats.likeCount--;
      }
      ElMessage.success(item.isLiked ? "点赞成功" : "已取消点赞");
    } else {
      ElMessage.error(response?.message || "点赞失败");
    }
  } catch (error) {
    console.error("点赞失败:", error);
    ElMessage.error("点赞失败");
  }
};

// 收藏处理
const handleCollect = async (item) => {
  // 检查登录状态
  if (!userStore.isLoggedIn) {
    ElMessage.warning("请先登录");
    return;
  }

  try {
    let response;
    // 目前只有文章支持收藏功能
    if (item.type === "article") {
      response = await toggleCollectArticle(item.id);
    } else {
      ElMessage.info("该类型内容暂不支持收藏");
      return;
    }

    if (response && response.code === 200) {
      // 更新本地状态
      item.isCollected = !item.isCollected;
      if (item.isCollected) {
        item.stats.collectCount++;
      } else {
        item.stats.collectCount--;
      }
      ElMessage.success(item.isCollected ? "收藏成功" : "已取消收藏");
    } else {
      ElMessage.error(response?.message || "收藏失败");
    }
  } catch (error) {
    console.error("收藏失败:", error);
    ElMessage.error("收藏失败");
  }
};

// 评论处理
const handleComment = (item) => {
  // 跳转到详情页面的评论区
  let routeName;
  let targetId;

  if (item.type === "question") {
    routeName = "QuestionDetail";
    targetId = item.id;
  } else if (item.type === "article") {
    routeName = "ArticleDetail";
    targetId = item.id;
  } else if (item.type === "answer") {
    // 回答的评论需要跳转到问题详情页
    routeName = "QuestionDetail";
    targetId = item.questionInfo?.id || item.id;
  }

  if (routeName && targetId) {
    router.push({
      name: routeName,
      params: { id: targetId },
      hash: "#comments",
    });
  } else {
    ElMessage.warning("无法跳转到评论区");
  }
};

// 分享处理
const handleShare = async (item) => {
  try {
    // 构建正确的分享链接
    let shareUrl;
    if (item.type === "question") {
      shareUrl = `${window.location.origin}/question/${item.id}`;
    } else if (item.type === "article") {
      shareUrl = `${window.location.origin}/article/${item.id}`;
    } else if (item.type === "answer") {
      shareUrl = `${window.location.origin}/question/${
        item.questionInfo?.id || item.id
      }`;
    } else {
      shareUrl = `${window.location.origin}/${item.type}/${item.id}`;
    }

    // 使用工具函数进行分享
    const result = await shareContent({
      title:
        item.title ||
        (item.content ? item.content.substring(0, 50) + "..." : "quora内容"),
      text: item.summary || item.content?.substring(0, 100),
      url: shareUrl,
    });

    if (result.success) {
      if (result.method === "clipboard") {
        ElMessage.success("链接已复制到剪贴板");
      }
      // 原生分享成功时不显示消息，因为系统会有自己的反馈
    } else {
      if (result.reason === "cancelled") {
        // 用户取消分享，不显示错误消息
        return;
      }

      // 分享和复制都失败，显示链接让用户手动复制
      ElMessage({
        message: `请手动复制链接：${shareUrl}`,
        type: "info",
        duration: 10000,
        showClose: true,
      });
    }
  } catch (error) {
    console.error("分享失败:", error);
    ElMessage.error("分享失败，请稍后重试");
  }
};

// 快捷操作处理
const handleQuickAction = () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning("请先登录");
    router.push("/login");
    return;
  }
  // 点击输入框，默认跳转到提问页面
  handleAskQuestion();
};

const handleAskQuestion = () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning("请先登录");
    router.push("/login");
    return;
  }
  router.push("/question/create");
};

const handleCreateAnswer = () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning("请先登录");
    router.push("/login");
    return;
  }
  // 跳转到问题列表或搜索页面，让用户选择要回答的问题
  ElMessage.info("请在问题详情页面进行回答");
};

const handleCreatePost = () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning("请先登录");
    router.push("/login");
    return;
  }
  router.push("/article/create");
};

// 页面初始化
onMounted(() => {
  loadRecommendData();
});
</script>

<style lang="scss" scoped>
.home-page {
  min-height: 100vh;
  background: #fafafa;
}

// 快捷创建区域
.quick-actions {
  position: sticky;
  top: $header-height;
  z-index: 11;
}

.quick-actions-card {
  margin: 10px auto;
  background: #ffffff;
  border: 1px solid #dee0e1;
  border-radius: 8px;
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  cursor: pointer;

  &:hover {
    background: #fafafa;
  }
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  flex-shrink: 0;

  &.default-avatar {
    background: #2e69ff;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #ffffff;
    font-size: 16px;
    font-weight: 600;
  }
}

.action-input {
  flex: 1;
  // border: none;
  height: 30px;
  background: transparent;
  border-radius: 15px;
  border: 1px solid #dee0e1;
  text-indent: 12px;
  outline: none;
  font-size: 14px;
  color: #939598;
  cursor: pointer;

  &::placeholder {
    color: #939598;
  }
}

.card-footer {
  display: flex;
  align-items: center;
  // border-top: 1px solid #dee0e1;
  height: 46px;
}

.action-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px 16px;
  border: none;
  background: transparent;
  font-size: 13px;
  font-weight: 500;
  color: #636466;
  cursor: pointer;
  transition: background-color 0.2s ease;

  &:hover {
    background: #f7f7f8;
  }

  svg {
    color: #939598;
  }

  span {
    color: #636466;
  }
}

.divider {
  width: 1px;
  height: 24px;
  background: #dee0e1;
}

.home-tabs {
  background: $background-color;
  border-bottom: 1px solid $border-color;
  position: sticky;
  top: calc($header-height + 115px);
  z-index: 10;
}

.tabs-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  padding: 0 20px;
}

.tab-item {
  padding: 16px 24px;
  font-size: 15px;
  font-weight: 500;
  color: $text-secondary;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.2s ease;

  &:hover {
    color: $text-color;
  }

  &.active {
    color: $primary-color;
    border-bottom-color: $primary-color;
  }
}

.home-content {
  width: 100%;
  padding: 0;
}

.content-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.loading-container {
  padding: 24px;
}

.load-more {
  text-align: center;
  padding: 24px;
}

.no-more {
  text-align: center;
  padding: 24px;
  color: $text-secondary;
  font-size: 14px;
}

.login-prompt {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.prompt-content {
  text-align: center;

  h3 {
    margin: 16px 0 8px;
    color: $text-color;
    font-size: 18px;
  }

  p {
    margin: 0 0 24px;
    color: $text-secondary;
    font-size: 14px;
  }
}

@media (max-width: 768px) {
  .quick-actions {
    padding: 8px;
  }

  .quick-actions-card {
    max-width: 100%;
    margin: 0;
  }

  .card-header {
    padding: 10px 12px;
  }

  .user-avatar {
    width: 36px;
    height: 36px;

    &.default-avatar {
      font-size: 14px;
    }
  }

  .action-input {
    font-size: 13px;
  }

  .action-btn {
    padding: 8px 12px;
    font-size: 12px;
    gap: 6px;

    svg {
      width: 16px;
      height: 16px;
    }

    span {
      display: none;
    }
  }

  .divider {
    height: 20px;
  }

  .home-tabs {
    top: calc($header-height + 74px);
  }

  .tabs-container {
    padding: 0 12px;
  }

  .tab-item {
    padding: 12px 16px;
    font-size: 14px;
  }

  .home-content {
    padding: 16px 12px;
  }
}
</style>
